package test.login;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Login extends HttpServlet {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO 自動生成されたメソッド・スタブ
		doAttrivute(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO 自動生成されたメソッド・スタブ
		doAttrivute(req, resp);
	}

	protected void doAttrivute(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String loginId = req.getParameter("loginId");
		String loginPass = req.getParameter("loginPass");
		String loginCheck = req.getParameter("loginCheck");

		/* 入力チェック開始 */
		boolean errFlg = false;
		String errMsg = "";

		/* 必須 */
		if (!InputCheck.Required(loginId) || !InputCheck.Required(loginPass)) {
			errFlg = true;
			errMsg = "Required Error";
		}

		if (errFlg) {
			req.setAttribute("errMsg", errMsg);
			req.getRequestDispatcher("/index.jsp").forward(req, resp);
		} else {

			UserController uc = new UserController();
			UserSearch us = new UserSearch();

			us.setId(loginId);
			us.setUser(loginPass);
			us.setAdminFlg(loginCheck);

			List<User> userList = uc.checkLogin(us);

			if (userList.size() > 0) {
				if ("1".equals(loginCheck)
						&& userList.get(0).getAdminFlg() == '1') {
					req.getRequestDispatcher("/userlist").forward(req, resp);
				} else {
					req.getRequestDispatcher("/read").forward(req, resp);
				}
			} else {
				errMsg = "Login ID and Pass Error";
				req.setAttribute("errMsg", errMsg);
				req.getRequestDispatcher("/index.jsp").forward(req, resp);
			}
		}
	}
}
